package com.ytjj.qmyx.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ytjj.common.utils.HttpClientUtil;
import com.ytjj.qmyx.admin.config.SupplyApiConfig;
import com.ytjj.qmyx.admin.dao.OrdersDao;
import com.ytjj.qmyx.admin.dao.ReturnGoodsDao;
import com.ytjj.qmyx.admin.dao.ReturnRegisterDao;
import com.ytjj.qmyx.admin.model.request.UpdateOrderStatusRequest;
import com.ytjj.qmyx.admin.model.request.UsersBalanceRecordRequest;
import com.ytjj.qmyx.admin.service.CommonRefundOrder;
import com.ytjj.qmyx.admin.service.UsersBalanceRecordService;
import com.ytjj.qmyx.mall.mapper.OrdersInfoMapper;
import com.ytjj.qmyx.mall.mapper.OrdersMapper;
import com.ytjj.qmyx.mall.mapper.OrdersRefundMapper;
import com.ytjj.qmyx.mall.mapper.ProductMapper;
import com.ytjj.qmyx.mall.model.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.LinkedMap;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class CommonRefundOrderImpl implements CommonRefundOrder {

    @Resource
    private OrdersRefundMapper refundMapper;
    @Resource
    private ReturnGoodsDao returnGoodsDao;
    @Resource
    private OrdersInfoMapper ordersInfoMapper;
    @Resource
    private OrdersDao ordersDao;
    @Resource
    private ReturnRegisterDao returnRegisterDao;
    @Resource
    private UsersBalanceRecordService usersBalanceRecordService;
    @Resource
    private SupplyApiConfig supplyApiConfig;
    @Resource
    private OrdersMapper ordersMapper;
    @Resource
    private ProductMapper productMapper;

    @Override
    public void handleRefundOrder(String outRefundNo,String xml) {

        log.info("退款成功------------>");
        OrdersRefundExample example = new OrdersRefundExample();
        example.createCriteria()
                .andRefundNoEqualTo(outRefundNo);

        List<OrdersRefund> refundList = refundMapper.selectByExample(example);
        OrdersRefund ordersRefund=refundList.get(0);
        OrdersInfo ordersInfo = ordersInfoMapper.selectByPrimaryKey(ordersRefund.getOrdersInfoId());
        // 退款表状态更新
        ordersRefund.setStatus(2);
        ordersRefund.setResText(JSONObject.toJSONString(xml));
        refundMapper.updateByPrimaryKeySelective(ordersRefund);

        // 同步退货管理中的退货状态
        ReturnGoods returnGoodsInfo = returnGoodsDao.getReturnGoodsByOid(ordersRefund.getOrdersInfoId());
        if (returnGoodsInfo != null) {
            returnGoodsDao.returnGoodsSuccess(returnGoodsInfo.getId());
        }
        // 3.查询订单
        Orders orders = ordersMapper.selectByPrimaryKey(ordersInfo.getOrderId());
        // 4.查询退货单
        ReturnGoods returnGoods = returnGoodsDao.selectReturnGoodsByWaitBackAmount(ordersInfo.getId());
        //交易关闭原因
        String closeRemarks = getCloseRemarks(returnGoodsInfo);
        // 订单详情修改 退款单状态已完成的才更新订单状态
        String orderInfoStatus = ordersInfo.getOrderinfoStatus();
        if (returnGoods.getStatus()==4){
            orderInfoStatus ="4";
        }
        ordersDao.updateStatusByOid(ordersInfo.getId(), orderInfoStatus,closeRemarks);//------------------------退款成功改为已关闭

        // 原路返回页中订单详情状态改为已退款
        returnRegisterDao.modifiedReturnRegister(ordersInfo.getId());

        // 订单修改 (只有所有详情中的订单状态为退款，主订单状态才改为退款)
        List<OrdersInfo> ordersInfoList = ordersDao.getAllOrdersInfoByOrderId(orders.getId());
        if (!CollectionUtils.isEmpty(ordersInfoList)) {
            int index = 0;
            for (OrdersInfo info : ordersInfoList) {
                if (info.getOrderinfoStatus().equals("6")) {
                    index += 1;
                }
            }
            if (index == ordersInfoList.size()) {
                Orders order = new Orders();
                order.setOrderStatus("4");//------------------------退款成功改为已关闭
                order.setIsRefund(1);
                order.setRefundNo(ordersRefund.getRefundNo());
                OrdersExample ordersExample = new OrdersExample();
                ordersExample.createCriteria()
                        .andOrderNoEqualTo(ordersRefund.getOrderNo());
                ordersMapper.updateByExampleSelective(order, ordersExample);

                // 原路返回页中主订单状态改为已退款
                returnRegisterDao.updateRegisterOrderStatus(ordersInfo.getId());
            }
        }
        if (null != returnGoods.getAfterType() && returnGoods.getAfterType() == 1){
            //售后类型为退款 把库存加回来
            try {
                Product product = productMapper.selectByPrimaryKey(ordersInfo.getProductId());
                subAndAddStock(ordersInfo.getChildOrderNo(),ordersInfo.getProductSum(),product.getIsZeroProduct(),"add");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //退抵扣金额
        //退款金额分几个情况处理
        try {
            addDeductionMoney(returnGoods,orders, ordersRefund);
        } catch (Exception e) {
            log.error("=========退款加抵扣金额失败========={}", e);
        }
        try {
            querySupplyChainOrderInfo(ordersInfo.getChildOrderNo(),returnGoods.getServiceNo());
        } catch (Exception e) {
            log.error("=========退款修改供应链订单失败========={}", e);
        }
    }

    /**
     * 获取交易关闭原因
     * @param returnGoodsInfo
     * @return
     */
    public String getCloseRemarks(ReturnGoods returnGoodsInfo) {
        String closeRemarks = "";
        if (returnGoodsInfo.getAfterType() == 1) {
            closeRemarks = "订单已申请退款";
        } else if (returnGoodsInfo.getAfterType() == 2) {
            closeRemarks = "订单已申请退货退款";
        } else if (returnGoodsInfo.getAfterType() == 3) {
            closeRemarks = "订单已申请仅退款";
        }
        return closeRemarks;
    }

    /**
     *  更新供应链订单状态
     *      * 销售端调用 （当销售端退款后，需要修改订单状态）
     */
    public void querySupplyChainOrderInfo(String childOrderNo,String serviceNo) {
        UpdateOrderStatusRequest updateOrderStatusRequest = new UpdateOrderStatusRequest();
        updateOrderStatusRequest.setChildOrderNo(childOrderNo);
        updateOrderStatusRequest.setShopId(supplyApiConfig.getShopId());
        updateOrderStatusRequest.setOrderStatus(4);
        String json = JSON.toJSONString(updateOrderStatusRequest);
        HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/order/updateOrderStatus", json, supplyApiConfig.getHeadsMap());

        YxReturnGoods yxReturnGoodsRequest = new YxReturnGoods();
        yxReturnGoodsRequest.setServiceNo(serviceNo);
        yxReturnGoodsRequest.setStatus(9);
        updateReturnGoods(yxReturnGoodsRequest);
    }

    /**
     * 抵扣金额退款
     * @param orders
     * @param ordersRefund
     */
    public void addDeductionMoney(ReturnGoods returnGoods, Orders orders, OrdersRefund ordersRefund) {
        int amount = returnGoods.getAmount().multiply(new BigDecimal(100)).intValue();
        //退抵扣金额
        if (null != orders.getDeductionMoney() && orders.getDeductionMoney().compareTo(new BigDecimal(0)) > 0){
            //退款金额分几个情况处理
            OrdersInfoExample ordersInfoExample = new OrdersInfoExample();
            ordersInfoExample.createCriteria().andOrderIdEqualTo(orders.getId());
            List<OrdersInfo> ordersInfos = ordersInfoMapper.selectByExample(ordersInfoExample);
            if (ordersInfos.size() > 0 && ordersInfos.size() < 2) {
                UsersBalanceRecordRequest usersBalanceRecordRequest = new UsersBalanceRecordRequest();
                usersBalanceRecordRequest.setBalance(returnGoods.getAmount().subtract(orders.getRealTotalMoney()));
                usersBalanceRecordRequest.setSource("REFUND");
                usersBalanceRecordRequest.setType("ADD");
                usersBalanceRecordRequest.setUserId(orders.getUserId());
                usersBalanceRecordService.insertRecord(usersBalanceRecordRequest);
            } else {
                if (null == orders.getRealTotalMoneyRefund()) {
                    int realTotalMoney = orders.getRealTotalMoney().multiply(new BigDecimal(100)).intValue();

                    if (amount > realTotalMoney) {
                        UsersBalanceRecordRequest usersBalanceRecordRequest = new UsersBalanceRecordRequest();
                        BigDecimal realTotalMoneyRefund = new BigDecimal(amount - realTotalMoney).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_CEILING);
                        usersBalanceRecordRequest.setBalance(realTotalMoneyRefund);
                        usersBalanceRecordRequest.setSource("REFUND");
                        usersBalanceRecordRequest.setType("ADD");
                        usersBalanceRecordRequest.setUserId(orders.getUserId());
                        usersBalanceRecordService.insertRecord(usersBalanceRecordRequest);
                        orders.setRealTotalMoneyRefund(new BigDecimal(0));
                        orders.setDeductionMoneyRefund(orders.getDeductionMoney().subtract(orders.getRealTotalMoney()));
                        ordersMapper.updateByPrimaryKeySelective(orders);
                    } else {
                        orders.setRealTotalMoneyRefund(new BigDecimal(realTotalMoney - ordersRefund.getRefundFee()).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_CEILING));
                        orders.setDeductionMoneyRefund(orders.getDeductionMoney());
                        ordersMapper.updateByPrimaryKeySelective(orders);
                    }

                } else {
                    int realTotalMoneyRefund = orders.getRealTotalMoneyRefund().multiply(new BigDecimal(100)).intValue();
                    if (amount > realTotalMoneyRefund) {
                        BigDecimal money = new BigDecimal(amount - realTotalMoneyRefund).divide(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP);
                        UsersBalanceRecordRequest usersBalanceRecordRequest = new UsersBalanceRecordRequest();
                        usersBalanceRecordRequest.setBalance(money);
                        usersBalanceRecordRequest.setSource("REFUND");
                        usersBalanceRecordRequest.setType("ADD");
                        usersBalanceRecordRequest.setUserId(orders.getUserId());
                        usersBalanceRecordService.insertRecord(usersBalanceRecordRequest);
                        orders.setRealTotalMoneyRefund(new BigDecimal(0));
                        orders.setDeductionMoneyRefund(orders.getDeductionMoney().subtract(money));
                        ordersMapper.updateByPrimaryKeySelective(orders);
                    } else {
                        orders.setRealTotalMoneyRefund(orders.getRealTotalMoneyRefund().subtract(new BigDecimal(ordersRefund.getRefundFee()).divide(new BigDecimal(100).setScale(2, BigDecimal.ROUND_CEILING))));
                        orders.setDeductionMoneyRefund(orders.getDeductionMoney());
                        ordersMapper.updateByPrimaryKeySelective(orders);
                    }
                }
            }
        }

    }

    /**
     * 扣减或退还库存
     * @param num 商品数量
     * @param type sub-扣减 add-退还
     * @return
     */public void subAndAddStock( String orderNo, Integer num,Integer isZeroProduct, String type) {
        Map<String,String> map = new LinkedMap();
        map.put("orderNo", orderNo);
        map.put("num", String.valueOf(num));
        map.put("isZeroProduct", String.valueOf(isZeroProduct));
        map.put("type", type);
        HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/stock/subAndAddStock", map, supplyApiConfig.getHeadsMap());
    }

    /**
     * 更新供应链售后信息
     */
    public void updateReturnGoods(YxReturnGoods request){
        request.setShopId(supplyApiConfig.getShopId());
        String json = JSON.toJSONString(request);
        HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/returnGoods/updateReturnGoods", json, supplyApiConfig.getHeadsMap());
    }
}
